<?php  if ( ! defined('BASE_PATH')) exit('No direct script access allowed');
/////////////////////////////////////////////////////////////////////////////
//
// SuperPHP - 快速的中文PHP框架
//
// @package		SuperPHP
// @author		hmw@superphp.org
// @copyright	Copyright (c) 2010, SuperPHP.ORG
// @license		http://www.superphp.org/user_guide/license.html
// @link		http://www.superphp.org
// @since		Version 1.0
//
// 许可协议请查看 http://www.SuperPHP.org/
//
/////////////////////////////////////////////////////////////////////////////

// ------------------------------------------------------------------------

/**
 * Database Cache Class
 *
 * @category	Database
 * @author		ExpressionEngine Dev Team
 * @link		http://codeigniter.com/user_guide/database/
 */
class Super_Db_Cache {

	var $db;	// allows passing of db object so that multiple database connections and returned db objects can be supported

	/**
	 * Constructor
	 *
	 * Grabs the CI super object instance so we can access it.
	 *
	 */
	public function  __construct($db=null){
		// Assign the main CI object to $this->CI
		// and load the file helper since we use it a lot
		if($db == null)$this->db = Super_Registry::get('db');
        else $this->db = $db;
	}

	// --------------------------------------------------------------------

	/**
	 * Set Cache Directory Path
	 *
	 * @access	public
	 * @param	string	the path to the cache directory
	 * @return	bool
	 */
	function check_path($path = ''){
		if ($path == ''){
			if ($this->db->cachedir == ''){
				return $this->db->cache_off();
			}

			$path = $this->db->cachedir;
		}

		// Add a trailing slash to the path if needed
		$path = preg_replace("/(.+?)\/*$/", "\\1/",  $path);

		if ( ! is_dir($path) OR ! is_really_writable($path)){
			// If the path is wrong we'll turn off caching
			return $this->db->cache_off();
		}

		$this->db->cachedir = $path;
		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Retrieve a cached query
	 *
	 * The URI being requested will become the name of the cache sub-folder.
	 * An MD5 hash of the SQL statement will become the cache file name
	 *
	 * @access	public
	 * @return	string
	 */
	function read($sql){
		if ( ! $this->check_path()){
			return $this->db->cache_off();
		}

		$segment_one = $this->db->database;

		$segment_two = $this->get_table($sql);

		$filepath = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'.md5($sql);

		if (FALSE === ($cachedata = read_file($filepath))){
			return FALSE;
		}

		return unserialize($cachedata);
	}

	// --------------------------------------------------------------------

	/**
	 * Write a query to a cache file
	 *
	 * @access	public
	 * @return	bool
	 */
	function write($sql, $object){
		if ( ! $this->check_path()){
			return $this->db->cache_off();
		}

		$segment_one = $this->db->database;

		$segment_two = $this->get_table($sql);

		$dir_path = $this->db->cachedir.$segment_one.'+'.$segment_two.'/';

		$filename = md5($sql);

		if ( ! @is_dir($dir_path)){
			if ( ! @mkdir($dir_path, DIR_WRITE_MODE)){
				return FALSE;
			}

			@chmod($dir_path, DIR_WRITE_MODE);
		}

		if (write_file($dir_path.$filename, serialize($object)) === FALSE){
			return FALSE;
		}

		@chmod($dir_path.$filename, DIR_WRITE_MODE);
		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Delete cache files within a particular directory
	 *
	 * @access	public
	 * @return	bool
     */
    function delete($sql) {
        $segment_one  = $this->db->database;
        
        $segment_two = $this->get_writable_table($sql);

        $dir_path = $this->db->cachedir.$segment_one.'+'.$segment_two.'/';

        delete_files($dir_path, TRUE);
	}

	// --------------------------------------------------------------------

	/**
	 * Delete all existing cache files
	 *
	 * @access	public
	 * @return	bool
	 */
	function delete_all(){
		delete_files($this->db->cachedir, TRUE);
	}

    /**
     * 从select语句中提取表名
     * @param <string> $sql
     * @return <string> $table 表名
     */
    function get_table($sql){
        $pattern = '/(?i)\bfrom\b(?![^\[\]]*\])\s+(\[[^\[\]]+\]|\S+)/';
        $table = 'default';
        if(preg_match($pattern, $sql,$arr)){
            $table = strtolower($arr[1]);
        }
        return $table;
    }

    function get_writable_table($sql){
        $pattern = '/(?i)\b(INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE)\b(?![^\[\]]*\])\s+(\[[^\[\]]+\]|\S+)/';
        $table = 'default';
        if(preg_match($pattern, $sql,$arr)){
            $table = strtolower($arr[1]);
        }
        return $table;
    }

}
